from alipay import AliPay
from django.http import JsonResponse, HttpResponseForbidden
from django.shortcuts import render
from django.views import View
from orders.models import OrderInfo
from tools.response_code import RETCODE
from django.conf import settings
from payment.models import Payment
import os
import logging
logger = logging.getLogger('django')

class PaymentVive(View):
    '''订单支付功能'''
    def get(self,request,order_id):
        # 判断一下用户是否登录
        user = request.user
        if not user.is_authenticated:
            return JsonResponse({'code': RETCODE.SESSIONERR, 'errmsg': '4101'})
        try:
            order = OrderInfo.objects.get(order_id=order_id,user=user,status=OrderInfo.ORDER_STATUS_ENUM['UNPAID'])
        except OrderInfo.DoesNotExist as e:
            logger.error(e)
            return HttpResponseForbidden('订单的id有误')
        # 创建一个支付对象，通过Alispay 类来实例化一个支付对象
        alipay_obj = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,
            app_private_key_string=open(
                os.path.join(settings.BASE_DIR,'keys/app_private_key.pem')
            ).read(),
            alipay_public_key_string=open(
                os.path.join(settings.BASE_DIR,'keys/alipay_public_key.pem')
            ).read(),
            sign_type='RSA2',
            debug=settings.DEBUG
        )
        #生成支付宝链接  固定链接+查询字符串（支付参数）
        order_string = alipay_obj.api_alipay_trade_page_pay(
            subject='美多商城',
            out_trade_no=order_id,
            total_amount=str(order.total_amount),
            return_url=settings.ALIPAY_RETURN_URL
        )
        alipay_url= settings.ALIPAY_URL+'?'+order_string
        return JsonResponse({'code':RETCODE.OK,'errmsg':'OK','alipay_url':alipay_url})


class PaymentStatusVive(View):
    '''支付成功后保存数据，并且修改订单的状态'''
    def get(self,request):
        # 获取一下支付宝返回来的签章，通过签章去做验证
        query_data = request.GET
        # 把这个类似字典的格式转换成python字典格式
        data = query_data.dict()
        print(data)
        # data{}
        signature = data.pop('sign')
        # 创建一个支付对象，通过Alispay 类来实例化一个支付对象
        alipay_obj = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,
            app_private_key_string=open(
                os.path.join(settings.BASE_DIR, 'keys/app_private_key.pem')
            ).read(),
            alipay_public_key_string=open(
                os.path.join(settings.BASE_DIR, 'keys/alipay_public_key.pem')
            ).read(),
            sign_type='RSA2',
            debug=settings.DEBUG
        )
        # 校验这个重定向是否是支付宝跳转回来的
        success = alipay_obj.verify(data, signature) # verify()返回的是个布尔值，是通过签章验证的结果
        if success:
            # 如果签章正确，通过浏览器发送来的参数获取到订单id 和 trade——id
            order_id = data.get('out_trade_no')
            trade_id = data.get('trade_no')
            # 数据的修改和保存
            Payment.objects.create(order_id=order_id,trade_id=trade_id)
            # OrderInfo.objects.filter(order_id=order_id,status=OrderInfo.ORDER_STATUS_ENUM['UNPAID']).update(
            #     status=OrderInfo.ORDER_STATUS_ENUM['UNSEND']
            # )
            OrderInfo.objects.filter(order_id=order_id,status=OrderInfo.ORDER_STATUS_ENUM['UNPAID']).update(
                status=OrderInfo.ORDER_STATUS_ENUM['UNCOMMENT']
            )

            return render(request,'pay_success.html',locals())
        else:
            return HttpResponseForbidden('非法请求')